{% extends "base.html" %}

{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}

{% block content %}
<h1>{{ title }}</h1>

<form id="recipe_form" name="create_recipe" action="" method="post">
	<table>
		{% for field in form %}
        <tr>
        	<td>{{ field.label_tag }}</td>
          	<td>{{ field }}{% if field.errors %} <strong>{{ field.errors }}</strong>{% endif %}</td>
        </tr>
		{% endfor %}
		<tr>
			<td>Ingredients</td>
			<td>
				<table id="ingredients" class="table">
					<tr>
						{% for form in formset.forms %}
							{% if forloop.first %}
								{% for field in form.visible_fields %}
									<th>{{ field.label_tag }}</th>
								{% endfor %}
							{% endif %}
						{% endfor %}
					</tr>
				{{ formset.management_form }}
				{% for form in formset.forms %}
					<tr class="last">
					{% for field in form %}
						{% if field.is_hidden %}
							{{ field }}
						{% else %}
							<td>{{ field }}{% if field.errors %} <strong>{{ field.errors }}</strong>{% endif %}</td>
						{% endif %}
			        {% endfor %}
			        </tr>
		        {% endfor %}
				</table>
				<input type="button" value="Add More" id="add_more">
				<script>
					$('#add_more').click(function() {
						cloneMore('tr.last:last', '{{ form_type }}');
					});
				</script>
			</td>
		</tr>
	</table>
	
	<input id="submit_button" type="submit" value="{{ button }}" />
</form>

<script type="text/javascript">
	$(function() {
    	$('#recipe_form :input:visible:first').focus()
	});
	
	/* Source: http://stackoverflow.com/questions/501719/dynamically-adding-a-form-to-a-django-formset-with-ajax */
	function cloneMore(selector, type) {
	    var newElement = $(selector).clone(true);
	    var total = $('#id_' + type + '-TOTAL_FORMS').val();
	    newElement.find(':input').each(function() {
	        var name = $(this).attr('name').replace('-' + (total-1) + '-','-' + total + '-');
	        var id = 'id_' + name;
	        $(this).attr({'name': name, 'id': id}).val('').removeAttr('checked');
	    });
	    newElement.find('label').each(function() {
	        var newFor = $(this).attr('for').replace('-' + (total-1) + '-','-' + total + '-');
	        $(this).attr('for', newFor);
	    });
	    total++;
	    $('#id_' + type + '-TOTAL_FORMS').val(total);
	    $(selector).after(newElement);
	}
</script>
{% endblock %}